<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col >
        <el-card>
          <div class="filter-container">
            <label style="margin-left: 20px;">分级: </label>
            <el-select style="margin-left: 10px;" class="filter-item"  v-model="listQuery.level[0]" placeholder="选择分级">
              <el-option
                v-for="item in levels"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <label> ~ </label>
            <el-select  class="filter-item"  v-model="listQuery.level[1]" placeholder="选择分级">
              <el-option
                v-for="item in levels"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-date-picker v-model="listQuery.date_range" :picker-options="pickerOptions" class="filter-item"
                            clearable
                            end-placeholder="结束日期"
                            range-separator="至"
                            start-placeholder="开始日期"
                            style="margin-left:20px"
                            type="daterange"
                            unlink-panels
                            @change="handleDateChange"
                            value-format="yyyy-MM-dd">
            </el-date-picker>
            <el-button v-if="checkPermission('查询设备')" class="filter-item" icon="el-icon-search" style="margin-left:40px"
                       type="primary"
                       @click="getDeviceList">
              查询
            </el-button>
            <el-button  style="margin-left: 10px" class="filter-item" type="primary" icon="el-icon-upload" @click="importLevels">
              导入
            </el-button>
            <el-button  :loading="exportLoading" class="filter-item"
                       icon="el-icon-download" style="margin-left: 10px" type="primary" @click="exportLeakage">
              导出
            </el-button>
          </div>
          <div class="app-container">
            <el-table
              :key="tableKey"
              ref="equipTable"
              v-loading="listLoading"
              :cell-style="{padding:0+'px'}"
              :data="list"
              :row-style="{height:40+'px'}"
              border
              fit
              height="700"
              highlight-current-row
              stripe
              style="width: 100%;"
            >
              <el-table-column
                type="index"
                width="30" label="#">
              </el-table-column>
              <el-table-column align="center" label="终端编号">
                <template slot-scope="{row}">
                  <span>{{ row.device_number }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="安装地址">
                <template slot-scope="{row}">
                  <span>{{ row.address }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="用水性质" >
                <template slot-scope="{row}">
                  <span>{{ row.user_case }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="漏水量" >
                <template slot-scope="{row}">
                  <span>{{ row.leakage_amount }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="漏损率" >
                <template slot-scope="{row}">
                  <span>{{ leakageRate(row) }}</span>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total>0" :limit.sync="listQuery.pageSize" :page.sync="listQuery.page" :total="total"
                        @pagination="getDeviceList"/>

            <el-dialog title="设备分级数据导入" :visible.sync="dialogImportVisible" custom-class="window-small-width">
              <el-form ref="importForm"   v-loading="formLoading" element-loading-text="正在导入数据，请稍后"
                       element-loading-spinner="el-icon-loading" label-position="right" label-width="60px">
                <el-form-item label="" prop="file" >
                  <el-upload
                    class="upload-demo"
                    drag
                    :headers="{'x-Token':token}"
                    action="/meter/device/level/import"
                    :on-success="handleImportSuccess"
                    :before-upload="beforeImport"
                  >
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传xls/xlsx文件，且不超过2M</div>
                    <div class="el-upload__tip" slot="tip">
                      尽量使用微软EXCEL,
                      <el-link type="primary" href="/static/表分级数据导入模板.xlsx?v=1.1">下载模板</el-link>
                    </div>

                  </el-upload>
                </el-form-item>
              </el-form>
            </el-dialog>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import {
  deviceGroups, deviceGroupsExport
} from "@/api/device";
import {checkPermission} from "@/utils/permission"
import { getToken } from '@/utils/auth'
import {exportMeter} from "@/api/meter";


export default {
  name: 'leakage',
  components: {Pagination},
  data() {
    return {
      dialogImportVisible: false,
      dialogStatus: 'create',
      formLoading:false,
      btnLoading: false,
      exportLoading: false,
      tableKey: 0,
      activeValue: 1,
      exportData: {
        list: [],
        headers: []
      },
      listLoading: true,
      list: [],
      total: 0,
      token:'',
      listQuery: {
        level:[1,2],
        date_range:[],
        page: 1,
        pageSize: 20,
      },
      levels:[
        {label:'一',value:1},{label:'二',value:2},{label:'三',value:3},{label:'四',value:4},{label:'五',value:5},{label:'六',value:6}
      ],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }],

      },
      fileTypes:['application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
    };
  },
  created() {
    this.getDeviceList()
    this.token = getToken()
  },
  methods: {
    checkPermission,
    exportDevices() {
    },
    getDeviceList() {
      this.listLoading = true
      let queryData = Object.assign({}, this.listQuery)
      queryData.device_size = queryData.device_size || 0
      deviceGroups(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleImportSuccess(res, file){
      this.formLoading =false
      this.importResult = res.message
      this.dialogImportVisible = false
      if(res.message.length == 0){
        this.$message.success('导入完成')
      }else{
        this.$message.error(res.message.join('<br>'))
      }
    },
    beforeImport(file){
      if (this.fileTypes.indexOf(file.type) == -1){
        this.$message.error('只允许导入微软excel文件');
        return false
      }
      if(file.size / 1024 / 1024 > 2 ){
        this.$message.error('文件大小限定2M');
        return false
      }
      this.formLoading = true
      return true
    },
    importLevels(){
      this.dialogImportVisible = true
    },
    leakageRate(row) {
      let rate = 0
      if(row.p_water_amount == 0) {
          return '-'
      }else {
        rate = ((row.p_water_amount- row.c_water_amount)/row.p_water_amount)*100
        return rate.toFixed(2)+'%'
      }
    },
    resetQueryParams() {
      this.listQuery = {
        id: 0,
        page: 1,
        pageSize: 20,
        name: ''
      }
    },
    handleDateChange(val) {
      if (val && val.length === 2) {
        const startDate = new Date(val[0]);
        const endDate = new Date(val[1]);
        const diffDays = (endDate - startDate) / (1000 * 60 * 60 * 24);
        if (diffDays > 365) {
          this.$message({
            message: '选择的时间段不能超过一年',
            type: 'warning'
          });
          this.listQuery.date_range = []; // 清空选中的日期
        }
      }
    },
    exportLeakage() {
      this.exportLoading = true
      const query = Object.assign({}, this.listQuery)
      query.page = 1
      query.pageSize = 5000
      deviceGroupsExport(query).then(res => {
        if (res.code == 20000) {
          this.exportData.list = res.data.list
          this.exportData.headers = res.data.headers
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = this.exportData.headers
            const data = this.exportData.list
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '漏水量数据统计',
              autoWidth: true,
              bookType: 'xlsx'
            })
            this.exportLoading = false
          })
        }
      })
    },
  }
}
</script>
